package com.xiaoxin.yixinai._frame.config;

import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.xiaoxin.yixinai._frame.base.BaseController;
import com.xiaoxin.yixinai._frame.base.ModuleCode;
import com.xiaoxin.yixinai._frame.utils.Config;
import com.xiaoxin.yixinai._frame.utils.MD5;
import com.xiaoxin.yixinai._frame.utils.StringUtils;
import com.xiaoxin.yixinai.role.MenuInfo;
import com.xiaoxin.yixinai.role.RoleInfo;
import com.xiaoxin.yixinai.role.RoleService;
import com.xiaoxin.yixinai.role.RoleUser;
import com.xiaoxin.yixinai.role.RoleUserService;

@Controller
public class LoginController extends BaseController {
	private final static String SECRET = "yxzn2018";

	@Resource
	private Config globalConfig;
	
	@Resource
	private RoleUserService roleUserService;
	
	@Resource
	private RoleService roleService;


	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(ModelMap model) {
		request.getSession().setAttribute("companyFullName", globalConfig.getCompanyFullName());
		request.getSession().setAttribute("companyShortName", globalConfig.getCompanyShortName());
		request.getSession().setAttribute("companyUrl", globalConfig.getCompanyUrl());
		return "login";
	}

	/**
	 * 到首页
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@ModuleCode(pValue = "home", value = "home")
	@RequestMapping("/")
	public String home(ModelMap model) throws ParseException {
		LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		// 查询用户的角色
		fillLoginUserRoleCode(loginUser);
		request.getSession().setAttribute("loginUser", loginUser.getUserInfo());
		
		// 设置登录用户的菜单权限
		setLoginUserSessionMenu(loginUser);
		
		request.getSession().setAttribute("redirectUri", globalConfig.getRedirectUri());
		request.getSession().setAttribute("questionnaireCompanyId", globalConfig.getQuestionnaireCompanyId());
		return "index";
	}
	
	private void fillLoginUserRoleCode(LoginUser loginUser) {
		RoleUser roleUser = roleUserService.findByUserId(loginUser.getUserInfo().getUserId());
		if (roleUser != null) {
			RoleInfo roleInfo = roleService.findOne(roleUser.getRoleId());
			if (roleInfo != null) {
				request.getSession().setAttribute("role_code", roleInfo.getRoleCode());
			}
		}
	}

	private void setLoginUserSessionMenu(LoginUser loginUser) {
		String role_code = (String) request.getSession().getAttribute("role_code");
		String menuJson = "[]";
		if(role_code.equals("admin")) {
			menuJson = globalConfig.getAdminMenu();
		}else if(role_code.equals("ep_platform")) {
			menuJson = globalConfig.getEpPlatformMenu();
		}
		List<MenuInfo> menuInfoList = JSONObject.parseArray(menuJson, MenuInfo.class);
		
		// 整理出菜单层级（二级）
		List<MenuInfo> firstLevelMenuList = new LinkedList<MenuInfo>();
		Map<String, List<MenuInfo>> secondLevelMenuMap = new LinkedHashMap<String, List<MenuInfo>>();
		for (MenuInfo menuInfo: menuInfoList) {
			if (menuInfo.getMenuLevel() == 1) {
				firstLevelMenuList.add(menuInfo);
			} else if (menuInfo.getMenuLevel() == 2) {
				List<MenuInfo> secondLevelMenuList = secondLevelMenuMap.get(menuInfo.getMenuParentId().toString());
				if (secondLevelMenuList == null) {
					secondLevelMenuList = new LinkedList<MenuInfo>();
					secondLevelMenuList.add(menuInfo);
				} else {
					secondLevelMenuList.add(menuInfo);
				}
				secondLevelMenuMap.put(menuInfo.getMenuParentId().toString(), secondLevelMenuList);
			}
		}
		
		
		request.getSession().setAttribute("firstLevelMenuList", firstLevelMenuList);
		request.getSession().setAttribute("secondLevelMenuMap", secondLevelMenuMap);
	}

	@RequestMapping(value = "/login/sysOutLogin", method = RequestMethod.POST)
	public void sysOutLogin(ModelMap model, HttpServletResponse response,
			@RequestParam(required = true) String companyId) {
		try {
			response.setHeader("ContentType", "text/json");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			/* String postUrl = outPath+"login/sysOutLogin.action"; */
			Long timestaLong = System.currentTimeMillis() / 1000;
			String timesStr = String.valueOf(timestaLong);
			MD5 md5 = new MD5();
			String sign = md5.encrypt(SECRET + companyId + timesStr);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("_clientType", "wap");
			paramMap.put("sign", sign);
			paramMap.put("timestamps", timestaLong);
			paramMap.put("companyId", companyId);
			Gson gson = new Gson();
			response.getWriter().write(gson.toJson(paramMap));
			response.getWriter().flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置左侧菜单body 折叠样式在session中存放、删除
	 * 
	 * @param request
	 * @param operation
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/setSessionSidebarCollapse", method = RequestMethod.POST)
	public Object setSessionSidebarCollapse(HttpSession session, String operation) {
		if (StringUtils.isNotEmpty(operation) && operation.equals("addClass")) {
			session.setAttribute("sidebar-collapse", "1");
		} else {
			session.removeAttribute("sidebar-collapse");
		}
		return SUCCESS();
	}
}
